package com.health.viewscontrols.medical.device.pef;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Handler;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.contec.sp.code.bean.DeviceType;
import com.contec.sp.code.bean.FVCData_B;
import com.contec.sp.code.bean.FVCData_BEXP;
import com.contec.sp.code.bean.FVCData_SP10;
import com.contec.sp.code.bean.PredictedValues_B;
import com.contec.sp.code.bean.PredictedValues_BEXP;
import com.contec.sp.code.bean.PredictedValues_SP10;
import com.contec.sp.code.bean.ResultData;
import com.contec.sp.code.bean.SdkConstants;
import com.contec.sp.code.bean.WaveData;
import com.contec.sp.code.callback.ConnectCallback;
import com.contec.sp.code.callback.OnOperateListener;
import com.contec.sp.code.connect.ContecSdk;
import com.empsum.blelibrary.bluetoothutils.Data;
import com.empsum.blelibrary.bluetoothutils.StrExchangeBytes;
import com.empsum.blelibrary.bluetoothutils.Utils;
import com.health.httpbean.model.UeModel;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.health.viewscontrols.medical.bean.PefBean;
import com.nova.health.ble.HexUtil;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;

import java.util.UUID;

/**
 * 恩普生 肺功能
 */
public class PEFActivity extends BaseDeviceActivity {

    private ContecSdk sdk;

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.pef);

        bt_start.setText("开始测量");
        sdk = new ContecSdk(getApplicationContext());
        sdk.init(true);
        sdk.setOnOperateListener(new OnOperateListener() {
            @Override
            public void onSuccess(final int operate, final ResultData data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (operate) {
                            case SdkConstants.OPERATE_SET_PARAMS:
//                                tvSetParams.setText("set params success");
                                break;
                            case SdkConstants.OPERATE_DELETE_DATA:
//                                tvDeleteData.setText("delete data success");
                                break;
                            case SdkConstants.OPERATE_GET_DATA:
                                if (data != null) {
                                    showResultData(data);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                });
            }

            @Override
            public void onFail(final int operate, final int errorCode) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // btnSync.setEnabled(true);
                        switch (operate) {
                            case SdkConstants.OPERATE_SET_PARAMS:
//                                tvSetParams.setText("errorCode = " + errorCode);
                                break;
                            case SdkConstants.OPERATE_DELETE_DATA:
//                                tvDeleteData.setText("errorCode = " + errorCode);
                                break;
                            case SdkConstants.OPERATE_GET_DATA:
//                                tvGetData.setText("errorCode = " + errorCode);
                                sdk.getData();
                                break;
                            default:
                                break;
                        }
                    }
                });
            }

            /**
             * 获取病例个数
             * @param totalNumber
             */
            @Override
            public void onDataInformation(final int totalNumber) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        tvGetDataInfo.setText(totalNumber + "");
//                    }
//                });
            }
        });

//        PefBean pefBean = new PefBean();
//        pefBean.setFvc("fvc");
//        pefBean.setFev05("fev05");
//        pefBean.setFev1("fev1");
//        pefBean.setFev1_fvc("fev1_fvc");
//        pefBean.setFev3("Fev3");
//        pefBean.setFev6("Fev6");
//        pefBean.setPef("Pef");
//        pefBean.setPef25("Pef25");
//        pefBean.setPef50("Pef50");
//        pefBean.setPef75("Pef75");
//        pefBean.setPef2575("Pef2575");
//        pefBean.setPeft("Peft");
//        pefBean.setEvol("Evol");
//
//        String json = GsonUtils.toJson(pefBean);
//        DeviceShowSaveData.getDataShow(json, "SP70B");
//        DeviceShowSaveData.savePEF(json);
    }

    /**
     * 连接回调
     */
    private ConnectCallback connectCallback = new ConnectCallback() {
        @Override
        public void onConnectStatus(final int status) {
            switch (status) {
                case SdkConstants.CONNECT_CONNECTED:
                    //连接成功
                    isConnected = true;
                    // 删除设备数据，始终保存测量只有一条结果数据
                    sdk.deleteData();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            bt_start.setText("同步数据");
                            blueToothState.setText("蓝牙已连接，测量完成请点击同步数据");
                            cancelProgressDialog();
//                            showProgressDialog("等待接收数据" + deviceEnum.getTitle() + "数据");
                        }
                    });
                    break;
                case SdkConstants.CONNECT_DISCONNECTED:
                case SdkConstants.CONNECT_DISCONNECT_EXCEPTION:
                case SdkConstants.CONNECT_DISCONNECT_SERVICE_UNFOUND:
                case SdkConstants.CONNECT_DISCONNECT_NOTIFY_FAIL:
                    //连接断开
                    isConnected = false;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            bt_start.setText("开始测量");
                            blueToothState.setText("蓝牙已断开连接");
                            cancelProgressDialog();
                        }
                    });
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onOpenStatus(final int status) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    tvStatus.setText("connectStatus = " + status);
//                    Log.e(TAG, "connectStatus = " + status);

                    switch (status) {
                        case SdkConstants.OPEN_SUCCESS:
                            //连接成功
                            isConnected = true;
                            break;
                        default:
                            break;
                    }
                }
            });
        }
    };

    @Override
    public void startDevice() {
        if (isConnected) {
            blueToothState.setText("蓝牙已连接，测量完成请点击同步数据");
            sdk.getData();
//            showProgressDialog("等待接收数据" + deviceEnum.getTitle() + "数据");
        } else {
            showProgressDialog("正在连接" + deviceEnum.getTitle() + "设备");
            blueToothState.setText("蓝牙开始连接");
            BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceEnum.getMac());
            sdk.connect(device, connectCallback);
        }
    }

    @Override
    public void update(String hexStr) {
    }

    private void showResultData(ResultData data) {
        if (data != null) {
            PefBean pefBean = new PefBean();
            DeviceType deviceType = data.getDeviceType();
            if (deviceType == (DeviceType.SP70B) || deviceType == (DeviceType.SP80B)) {
                if (data.getPredictedValues_B() != null) {
                    PredictedValues_B predictedValues_B = data.getPredictedValues_B();
                    pefBean.setFvc(predictedValues_B.getFVC());
                    pefBean.setFev1(predictedValues_B.getFEV1());
                    pefBean.setFev1_fvc(predictedValues_B.getFEV1_FVC());
                    pefBean.setPef(predictedValues_B.getPEF());
                }

                if (data.getFVCDatas_B() != null) {
                    for (int i = 0; i < data.getFVCDatas_B().size(); i++) {
                        FVCData_B fvcData_B = data.getFVCDatas_B().get(i);
//                        String date = fvcData_B.getYear() + "-" + fvcData_B.getMonth() + "-" + fvcData_B.getDay()
//                                + " " + fvcData_B.getHour() + ":" + fvcData_B.getMinute() + ":" + fvcData_B.getSecond();
                        pefBean.setFvc(fvcData_B.getFVC());
                        pefBean.setFev1(fvcData_B.getFEV1());
                        pefBean.setFev1_fvc(fvcData_B.getFEV1_FVC());
                        pefBean.setPef(fvcData_B.getPEF());
                    }
                } else {
                    ToastUtils.showShort("设备没有新数据");
                }
            } else if (deviceType == DeviceType.SP70BEXP || deviceType == DeviceType.SP80BEXP) {
                if (data.getPredictedValues_BEXP() != null) {
                    PredictedValues_BEXP predictedValues_BEXP = data.getPredictedValues_BEXP();
                    pefBean.setFvc(predictedValues_BEXP.getFVC());
                    pefBean.setFev1(predictedValues_BEXP.getFEV1());
                    pefBean.setFev1_fvc(predictedValues_BEXP.getFEV1_FVC());
                    pefBean.setPef(predictedValues_BEXP.getPEF());
                    pefBean.setPef25(predictedValues_BEXP.getFEF25());
                    pefBean.setPef50(predictedValues_BEXP.getFEF50());
                    pefBean.setPef75(predictedValues_BEXP.getFEF75());
                    pefBean.setPef2575(predictedValues_BEXP.getFEF2575());
                    pefBean.setFev3(predictedValues_BEXP.getFEV3());
                    pefBean.setFev6(predictedValues_BEXP.getFEV6());
                }
                if (data.getFVCDatas_BEXP() != null) {
                    for (int i = 0; i < data.getFVCDatas_BEXP().size(); i++) {
                        FVCData_BEXP fvcData_BEXP = data.getFVCDatas_BEXP().get(i);
                        pefBean.setFvc(fvcData_BEXP.getFVC());
                        pefBean.setFev05(fvcData_BEXP.getFEV05());
                        pefBean.setFev1(fvcData_BEXP.getFEV1());
                        pefBean.setFev1_fvc(fvcData_BEXP.getFEV1_FVC());
                        pefBean.setFev3(fvcData_BEXP.getFEV3());
                        pefBean.setFev6(fvcData_BEXP.getFEV6());
                        pefBean.setPef(fvcData_BEXP.getPEF());
                        pefBean.setPef25(fvcData_BEXP.getFEF25());
                        pefBean.setPef50(fvcData_BEXP.getFEF50());
                        pefBean.setPef75(fvcData_BEXP.getFEF75());
                        pefBean.setPef2575(fvcData_BEXP.getFEF2575());
                        pefBean.setPeft(fvcData_BEXP.getPEFT());
                        pefBean.setEvol(fvcData_BEXP.getEVOL());
                    }
                } else {
                    ToastUtils.showShort("设备没有新数据");
                }
//                if (data.getWaveDatas() != null) {
//                    for (int i = 0; i < data.getWaveDatas().size(); i++) {
//                        WaveData waveData = data.getWaveDatas().get(i);
//                        stringBuffer.append("波形点数 = " + waveData.getWaveCount() + "\n");
//                        for (int j = 0; j < waveData.getWaveCount(); j++) {
//                            stringBuffer.append("waveTime = " + waveData.getTimes()[j] + "   ");
//                            stringBuffer.append("waveSpeed = " + waveData.getSpeeds()[j] + "   ");
//                            stringBuffer.append("waveVolume = " + waveData.getVolumes()[j] + "\n");
//                        }
//                    }
//                }
            } else if (deviceType == DeviceType.SP10) {
                if (data.getPredictedValues_SP10() != null) {
                    PredictedValues_SP10 sp10ExpPredictedValues = data.getPredictedValues_SP10();
//                    stringBuffer.append("predicted_FVC = " + sp10ExpPredictedValues.getFVC() + "\n");
//                    stringBuffer.append("predicted_FEV1 = " + sp10ExpPredictedValues.getFEV1() + "\n");
//                    stringBuffer.append("predicted_FEV1_FVC = " + sp10ExpPredictedValues.getFEV1_FVC() + "\n");
//                    stringBuffer.append("predicted_PEF = " + sp10ExpPredictedValues.getPEF() + "\n");
//                    stringBuffer.append("predicted_FEF25 = " + sp10ExpPredictedValues.getFEF25() + "\n");
//                    stringBuffer.append("predicted_FEF50 = " + sp10ExpPredictedValues.getFEF50() + "\n");
//                    stringBuffer.append("predicted_FEF75 = " + sp10ExpPredictedValues.getFEF75() + "\n");
//                    stringBuffer.append("predicted_FEF2575 = " + sp10ExpPredictedValues.getFEF2575() + "\n");
//                    stringBuffer.append("predicted_FEV3 = " + sp10ExpPredictedValues.getFEV3() + "\n");
//                    stringBuffer.append("predicted_FEV6 = " + sp10ExpPredictedValues.getFEV6() + "\n");
                    pefBean.setFvc(sp10ExpPredictedValues.getFVC());
                    pefBean.setFev1(sp10ExpPredictedValues.getFEV1());
                    pefBean.setFev1_fvc(sp10ExpPredictedValues.getFEV1_FVC());
                    pefBean.setFev3(sp10ExpPredictedValues.getFEV3());
                    pefBean.setFev6(sp10ExpPredictedValues.getFEV6());
                    pefBean.setPef(sp10ExpPredictedValues.getPEF());
                    pefBean.setPef25(sp10ExpPredictedValues.getFEF25());
                    pefBean.setPef50(sp10ExpPredictedValues.getFEF50());
                    pefBean.setPef75(sp10ExpPredictedValues.getFEF75());
                    pefBean.setPef2575(sp10ExpPredictedValues.getFEF2575());
                }

                if (data.getFVCDatas_SP10() != null) {
                    for (int i = 0; i < data.getFVCDatas_SP10().size(); i++) {
                        FVCData_SP10 fvcData_SP10 = data.getFVCDatas_SP10().get(i);
//                        String date = fvcData_SP10.getYear() + "-" + fvcData_SP10.getMonth() + "-" +
//                                fvcData_SP10.getDay() + " " + fvcData_SP10.getHour() + ":" + fvcData_SP10.getMinute()
//                                + ":" + fvcData_SP10.getSecond();
//                        stringBuffer.append(date + "\n");
//                        stringBuffer.append("fvc = " + fvcData_SP10.getFVC() + "\n");
//                        stringBuffer.append("fev05 = " + fvcData_SP10.getFEV05() + "\n");
//                        stringBuffer.append("fev1 = " + fvcData_SP10.getFEV1() + "\n");
//                        stringBuffer.append("FEV1_fvc = " + fvcData_SP10.getFEV1_FVC() + "\n");
//                        stringBuffer.append("FEV3 = " + fvcData_SP10.getFEV3());
//                        stringBuffer.append("FEV6 = " + fvcData_SP10.getFEV6() + "\n");
//                        stringBuffer.append("PEF = " + fvcData_SP10.getPEF() + "\n");
//                        stringBuffer.append("FEF25 = " + fvcData_SP10.getFEF25() + "\n");
//                        stringBuffer.append("FEF50 = " + fvcData_SP10.getFEF50() + "\n");
//                        stringBuffer.append("FEF75 = " + fvcData_SP10.getFEF75() + "\n");
//                        stringBuffer.append("FEF2575 = " + fvcData_SP10.getFEF2575() + "\n");
//                        stringBuffer.append("PEFT = " + fvcData_SP10.getPEFT() + "\n");
//                        stringBuffer.append("EVOL = " + fvcData_SP10.getEVOL() + "\n");
                        pefBean.setFvc(fvcData_SP10.getFVC());
                        pefBean.setFev05(fvcData_SP10.getFEV05());
                        pefBean.setFev1(fvcData_SP10.getFEV1());
                        pefBean.setFev1_fvc(fvcData_SP10.getFEV1_FVC());
                        pefBean.setFev3(fvcData_SP10.getFEV3());
                        pefBean.setFev6(fvcData_SP10.getFEV6());
                        pefBean.setPef(fvcData_SP10.getPEF());
                        pefBean.setPef25(fvcData_SP10.getFEF25());
                        pefBean.setPef50(fvcData_SP10.getFEF50());
                        pefBean.setPef75(fvcData_SP10.getFEF75());
                        pefBean.setPef2575(fvcData_SP10.getFEF2575());
                        pefBean.setPeft(fvcData_SP10.getPEFT());
                        pefBean.setEvol(fvcData_SP10.getEVOL());
                    }
                } else {
                    ToastUtils.showShort("设备没有新数据");
//                    stringBuffer.append("设备没有新数据， Device has no new data");
                }
//                if (data.getWaveDatas() != null) {
//                    for (int i = 0; i < data.getWaveDatas().size(); i++) {
//                        WaveData waveData = data.getWaveDatas().get(i);
//                        stringBuffer.append("波形点数 = " + waveData.getWaveCount() + "\n");
//                        for (int j = 0; j < waveData.getWaveCount(); j++) {
//                            stringBuffer.append("waveTime = " + waveData.getTimes()[j] + "   ");
//                            stringBuffer.append("waveSpeed = " + waveData.getSpeeds()[j] + "   ");
//                            stringBuffer.append("waveVolume = " + waveData.getVolumes()[j] + "\n");
//                        }
//                    }
//                }
            }

            if (pefBean != null && pefBean.getFvc() != null) {
                String json = GsonUtils.toJson(pefBean);
                DeviceShowSaveData.getDataShow(json, "SP70B");
                DeviceShowSaveData.savePEF(json);
                runOnUiThread(() -> {
                    Log.e(TAG, "run: " + pefBean.toString());
                    tv_state.setText("");
                    tv_result.setText(pefBean.toString());
                    disconn();
                });
            }
        }

        //再次接收完数据后才能点击按钮
//        btnSync.setEnabled(true);
    }


    @Override
    public void disconnectDevice() {
        disconn();
    }

    private void disconn() {
        try {
            if (null != sdk) {
                sdk.stopLeScan();
                sdk.disconnect();
            }
            cancelProgressDialog();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            isConnected = false;
            mBleDevice.setConnect(false);
            mBleDevice.disconnect();
            mBleDevice.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
